package sk.fiit.lulco.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JPanel;

import sk.fiit.lulco.grafy.Graph;
import sk.fiit.lulco.grafy.Vertex;

public class GraphPanel extends JPanel {

	private static final long serialVersionUID = -3896839909654625904L;
	private Graph graph;
	
	
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (graph == null) {
			return;
		}
		
		int width = getWidth();
		int height = getHeight();
		int boardWidth = graph.getWidth();
		int boardHeight = graph.getHeight();
		int size = width / (boardWidth + 2) < height / (boardHeight + 2) ? width / (boardWidth + 2) : height / (boardHeight + 2); 
		for (int i = 0; i < boardWidth; i++) {
			for (int j = 0; j < boardHeight; j++) {
				if (i % 2 == j % 2) {
					g.setColor(Color.white);
				} else {
					g.setColor(Color.gray);
				}
				g.fillRect((1 + i) * size, (1 + j) * size, size, size);
			}
		}
		
		for (Vertex vertex: graph.getVertices()) {
			int modWidth = vertex.getId() % boardWidth;
			int del = vertex.getId() / boardWidth;
			if (modWidth > 0) {
				del = del + 1;
			}
			if (modWidth == 0) {
				modWidth = boardWidth;
			}
			int x = size * modWidth + size / 4;
			int y = size * del + size / 4;
			g.setColor(getColor(vertex.getColor()));
			g.fillOval(x, y, size / 2, size / 2);
		}
	}
	
	private Color getColor(int vertexColor) {
		int del = vertexColor / 6;
		int mod = vertexColor % 6;
		if (mod > 0 || vertexColor == 0) {
			del = del + 1;
		} else {
			mod = 6;
		}
		String binary = Integer.toBinaryString(mod);
		int length = binary.length();
		for (int i = 0; i < 3 - length; i++) {
			binary = "0" + binary;
		}
		int value = 255 / del;
		int r = Integer.parseInt(Character.toString(binary.charAt(0))) * value;
		int g = Integer.parseInt(Character.toString(binary.charAt(1))) * value;
		int b = Integer.parseInt(Character.toString(binary.charAt(2))) * value;
		
		return new Color(r, g, b);
	}
	
	@Override
	public Color getBackground() {
		return Color.lightGray;
	}
	
	@Override
	public Dimension getMinimumSize() {
		return new Dimension(150, 150);
	}
	
	public void setGraph(Graph graph) {
		this.graph = graph;
	}
}
